from django.shortcuts import render

from django.views import View
from django.http import HttpResponse

#图片验证码
class ImageCodeView(View):
    def get(self,request):
        """
        接收请求
        提取参数
        验证参数
        生成图片验证码　获取验证码
        保存图片验证码
        返回图片响应
        :param request:
        :return:
        """
        # 获取图片验证码　获取验证码内容
        from libs.captcha.captcha import captcha
        text,image = captcha.generate_captcha()
        # 连接redis
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        redis_cli.setex('imagecode',300,text)
        # 返回图片响应
        return HttpResponse(image,content_type='image/jpeg')



# 短信验证
from apps.users.models import User
from django.http import JsonResponse
import json
import re
class SmsCodeView(View):
    def post(self,request):
        # 接受参数
        body = request.body
        body_str = body.decode()
        data = json.loads(body_str)

        #　提取参数
        image_code = data.get('text')
        mobile = data.get('mobile')

        #验证参数
        import re
        from django import http
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '请输入正确的手机号!'})

        # try:
        #     mobile = User.objects.filter(mobile=mobile)
        # except Exception as e:
        #     return http.JsonResponse({'code': 400, 'errmsg': '手机号已存在!'})
        # else:
        imageCodeId = data.get('id')


        from django_redis import get_redis_connection

        redis_cli = get_redis_connection('code')
        redis_text = redis_cli.get('imagecode')

        redis_cli.delete(imageCodeId)
        if image_code.lower() != redis_text.decode().lower():
            return JsonResponse({'errno': 400, 'errmsg': '图片验证码错误'})
        # 生成验证码
        from random import randint
        sms_code = randint(100000, 999999)

        redis_cli.setex(mobile, 600, sms_code)

        from ronglian_sms_sdk import SmsSDK
        accId = '8a216da8762cb4570176c6061ff035f7'
        accToken = '807fc004007642468124374558947f16'
        appId = '8a216da8762cb4570176c60620e435fe'


        # 创建荣联运实例对象
        sdk = SmsSDK(accId, accToken, appId)
        # 发送条数
        tid = '1'
        # 用户电话
        mobile = '%s'%mobile
        # 验证码是１　　　有效时间是５分钟
        datas = (sms_code, 5)
        # 发送
        sdk.sendMessage(tid, mobile, datas)

        return JsonResponse({'errno':0,'errmsg':'发送成功'})